<template>
  <div class="tinymce-container editor-container">
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script>
import plugins from "./plugins";
import toolbar from "./toolbar";
// import uploadAPI from '@/api/upload'

export default {
  name: "Tinymce",
  props: {
    id: {
      type: String,
      default: function() {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      }
    },
    value: {
      type: String,
      default: ""
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      }
    },
    menubar: {
      type: String,
      default: "file edit insert view format table"
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      value_: "",
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        en: "en",
        zh: "zh_CN"
      }
    };
  },
  computed: {
    language() {
      return this.languageTypeList[this.$store.getters.language];
    }
  },
  watch: {
    value(newValue) {
      let content = newValue || "";
      if (newValue !== this.value_) {
        content = this._normalizeHtml(content);
      }
      // 从自己触发的内容更改不回填到编辑器(修复v-model双向绑定失效问题)
      if ((!this.hasChange || newValue !== this.value_) && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(content)
        );
      }

      if (this.fromSelf) {
        this.fromSelf = false;
      }
    },
    language() {
      this.destroyTinymce();
      this.$nextTick(() => this.initTinymce());
    }
  },
  mounted() {
    this.initTinymce();
  },
  activated() {
    this.initTinymce();
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        language: "zh_CN",
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin,
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;

          editor.addShortcut("ctrl+e", "remove all style", () => {
            editor.execCommand("selectAll");
            editor.execCommand("RemoveFormat");
          });

          // editor.on('paste', (event) => {
          //   console.log('paste')
          //   let html = event.clipboardData.getData('text/html')
          //   const text = event.clipboardData.getData('text/plain')
          //   html = html && this._normalizeHtml(html)
          //   setTimeout(() => {
          //     editor.setContent(html || text)
          //     editor.execCommand('RemoveFormat')
          //   }, 300)
          //   // event.clipboardData.setData('text/html', html)
          // })

          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            // 从自己触发的内容更改不回填到编辑器
            this.value_ = editor.getContent();
            const content = this.value_;
            this.$emit("input", content);
          });
        },
        setup(editor) {
          editor.on("FullscreenStateChanged", e => {
            _this.fullscreen = e.state;
          });
        },

        // 图片上传
        images_dataimg_filter(img) {
          return img;
        },
        async images_upload_handler(blobInfo, success, failure, progress) {
          progress(0);
          const formData = new FormData();
          formData.append("file", blobInfo.blob(), blobInfo.filename());
          // const resp = await uploadAPI.uploadImage(formData)
          // if (resp.code === '0') {
          //   success(resp.results)
          //   progress(100)
          // }
        }
      });
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand("mceFullScreen");
      }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      const _this = this;
      arr.forEach(v => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`);
      });
    },
    _normalizeHtml(html) {
      let content = html;
      const whiteTagPattern = /^(h1|h2|h3|h4|div|p|hr|form|label|input|select|texarea|img|iframe|ul|li|ol|dd|dl|dt|table|tr|td|th|thead|tbody|span|a|i|b|strong|font|red|sub|sup|small|em|br)$/;
      const pattern = /(<)(\/?[^\s<>]*)(\s*[^<>]*?)?\s*(>)/g;
      const whiteAttrPattern = /(?:href|style|src|border|origin-site|class|colspan|rowspan)\s*=\s*("|').*?\1/g;
      content = content.replace(pattern, function(g0, g1, g2, g3, g4) {
        const tag = g2 ? g2.replace("/", "") : "";
        if (!whiteTagPattern.test(tag)) {
          return "";
        }
        let attrs = "";
        if (g3) {
          const whiteAttrList = g3.match(whiteAttrPattern) || [];
          attrs = " " + whiteAttrList.join(" ");
        }

        return g1 + g2 + attrs + g4;
      });
      return content;
    }
  }
};
</script>

<style scoped>
.tinymce-container {
  position: relative;
}
.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
/deep/.mce-statusbar {
  display: none;
}
</style>
